package org.lei.gift.exception;

import org.lei.gift.syscode.SystemErrorCode;
import org.lei.gift.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //就是把当前的类交给Spring管理
public class GlobalExceptionHandler {

    // controller ---> service  --->mapper
    // 调用者<--- controller<--- service  <---e
    /*
        统一处理
          controller ---> service  --->mapper
           controller<-x- service  <---e
     ControllerAdvice <--
                根据错误类型做分发,返回具体的错误描述
        自定义异常
        规范所有的异常提示信息
        整合jsr303

     */



    @ExceptionHandler(Exception.class)
    public AjaxResult exception(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setMessage(SystemErrorCode.RESPONSE_CODE_500.getMsg())
                .setCode(SystemErrorCode.RESPONSE_CODE_500.getCode())
                ;
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult paramException(MethodArgumentNotValidException e){
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();

        StringBuilder sb = new StringBuilder();
        for (ObjectError allError : allErrors) {
            sb.append(allError.getDefaultMessage()).append(",");
        }

        return AjaxResult.me().setSuccess(false)
                .setMessage(sb.toString())
                .setCode(SystemErrorCode.RESPONSE_CODE_400.getCode())
                ;
    }

    @ExceptionHandler(RuntimeException.class)
    public AjaxResult runtimeException(RuntimeException e){
        e.printStackTrace();
         return AjaxResult.me().setSuccess(false).setMessage("系统异常"+e.getMessage());
    }
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessException(BusinessException e){
         e.printStackTrace();
         return AjaxResult.me().setSuccess(false)
                 .setMessage(e.getMsg()).setCode(e.getCode());
    }
}
